<template>
	<div class="images-list1">
		<el-upload
			ref="upload"
			:class="className"
			action="string"
			:data="paramsData"
			:limit="fileLimit"
			:show-file-list="showFile"
			:on-success="handleSuccess"
			:on-error="handleUploadError"
			:on-remove="handleRemove"
			:on-exceed="handleExceed"
			:on-preview="handlePreview"
			:multiple="fileLimit > 1"
			:list-type="listType"
			:file-list="fileList"
			:drag="dragable"
			:http-request="handleUploadFile"
		>
            <img v-if="showUrl" :src="showUrl" class="avatar" />
			<i v-else class="el-icon-plus avatar-uploader-icon"></i>
		</el-upload>
		<span v-if="loading && className === 'upload-demo'" class="cancel" @click="handleCancel"
			>取消上传</span
		>
	</div>
</template>
<script>

import {
	put,
	getUrl,
	cancelUpload
} from '@/components/Upload/uploadOss.js'

export default {
	name: 'NewUpload',
	props: {
		// 值
		value: [String, Object, Array],
		// 大小限制(MB)
		fileSize: {
			type: Number,
			default: 1
		},
		// 文件类型, 例如["doc", "xls", "ppt", "txt", "pdf"]
		fileType: {
			type: Array,
			default: () => []
		},
		// 文件列表类型 text/picture/picture-card
		listType: {
			type: String,
			default: 'picture'
		},
		// 是否显示提示
		isShowTip: {
			type: Boolean,
			default: true
		},
		// 最大允许上传个数
		fileLimit: {
			type: Number,
			default: 99
		},
		// 是否显示上传的文件列表
		showFile: {
			type: Boolean,
			default: false
		},
		// 文件上传样式class
		className: {
			type: String,
			default: 'upload-demo'
		},
		// 是否允许拖拽上传
		dragable: {
			type: Boolean,
			default: false
		},
		// 源数据
		uploadUrl: {
			type: String,
			default: ''
		},
		// 按钮显示的文案
		btnText: {
			type: String,
			default: '上传'
		},
		// 按钮大小
		btnSize: {
			type: String,
			default: 'mini'
		}
	},
	mounted(){
		this.showUrl = this.uploadUrl
	},
	data() {
		return {
			showUrl: '', // 返回服务器地址
			paramsData: {}, // 上传携带的参数，看需求要不要
			fileList: [],
			tempFileList: [], // 因为 fileList为只读属性，所以用了一个中间变量来进行数据改变的交互。
			imageUrl: '',
			loading: false,
			dialogVisible: false,
			allowUplad: true
		}
	},
	watch: {
		value: {
			handler: function (newVal) {
				this.tempFileList = newVal
			},
			immediate: true,
			deep: true
		}
	},
	computed: {
		// 是否显示提示
		showTip() {
			return this.isShowTip && (this.fileType || this.fileSize)
		},
		fileTypeName() {
			let typeName = ''
			this.fileType.forEach((item) => {
				typeName += `${item}，`
			})
			return typeName
		},
		fileAccept() {
			let fileAccept = ''
			this.fileType.forEach((element) => {
				fileAccept += `.${element},`
			})
			return fileAccept
		}
	},
	created() {
		if (this.value) {
			this.fileList = JSON.parse(JSON.stringify(this.value))
		}
		var token = null
		if (!JSON.parse(sessionStorage.getItem('tokenAll'))) {
			token = null
		} else {
			token = JSON.parse(sessionStorage.getItem('tokenAll')).token
		}
		this.paramsData = {
			token: token
		}
	},
	methods: {
		// 上传前校检格式和大小
		handleBeforeUpload(file) {
			let result = true
			if (this.fileType && this.fileType.length > 0 && file) {
				const isTypeOk = this.fileType.some((item) => {
					let fileExtension = ''
					if (file.name.lastIndexOf('.') > -1) {
						fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
					}
					if (fileExtension && fileExtension.indexOf(item) > -1) {
						return true
					} else {
						return false
						result = false
					}
				})
				if (!isTypeOk && file) {
					this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`)
					return false
					result = false
				}
			}
			// 校检文件大小
			if (this.fileSize && file) {
				const isLt = file.size / 1024 / 1024 < this.fileSize
				if (!isLt) {
					this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`)
					return false
					result = false
				}
			}
			return result
		},
		handleUploadError() {
			this.$message.error('上传失败, 请重试')
		},
		// 文件个数超出
		handleExceed() {
			this.$message.error(`超出上传文件个数,请检查！`)
		},
		// 图片预览
		handlePreview(file) {
			this.dialogVisible = true
		},
		// 文件上传成功的钩子
		handleSuccess(res, file, fileList) {
			console.log(res)
		},
		// 文件列表移除文件时的钩子
		handleRemove(file, fileList) {
			this.changeFileList(fileList)
		},
		// 文件列表改变的时候，更新组件的v-model的文的数据
		changeFileList(fileList) {
			const tempFileList = fileList.map((item) => {
				let tempItem = {
					name: item.name,
					url: item.response ? item.response.payload.imgUrl : item.url
				}
				return tempItem
			})
			this.$emit('input', tempFileList)
		},
		// 自定义上传
		handleUploadFile(option) {
			if (this.handleBeforeUpload(option.file)) {
				this.loading = true
				//获取上传后的url
				const _name = this.getDate() + '/' + option.file.uid + '.' + option.file.name.split('.')[1]
				put(_name, option.file).then((res) => {
					if (res) {
						getUrl(res.name).then((rel) => {
							this.showUrl = rel
							this.$emit('geImg', {
								class: this.className,
								key: _name,
								showUrl: rel
							})
							this.loading = false
							this.$refs.upload.clearFiles()
						})
					} else {
						this.$refs.upload.clearFiles()
					}
				})
			}
		},
		// 取消上传
		handleCancel() {
			cancelUpload().then((rel) => {
				if (rel) {
					this.$refs.upload.abort()
					this.loading = false
				}
			})
		},
		// 获取当前年月日
		getDate() {
			const date = new Date()
			var year = date.getFullYear()
			var month = date.getMonth() + 1
			var day = date.getDate()
			month = month > 9 ? month : '0' + month
			day = day < 10 ? '0' + day : day
			var today = year + month + day
			return today
		}
	}
}
</script>

<style lang="scss" scoped>
.avatar{
    width: 178px;
    height: 178px;
    display: block;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
</style>